package cn.wwk.notification.common.utils;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * The type Md 5 util.
 */
public class MD5Util {

    /**
     * Md 5 string.
     *
     * @param src the src
     * @return the string
     */
    public static String md5(String src) {
        return DigestUtils.md5Hex(src);
    }
    //客户端固定的salt，跟用户的密码做一个拼装
    private static final String salt = "1a2b3c4d";

    private static final int saltLength = 6;

    /**
     * Input pass to form pass string.
     *	客户端固定的salt，跟用户的密码做一个拼装
     * @param inputPass the input pass
     * @return the string
     * 一次加密
     */
    public static String inputPassToFormPass(String inputPass) {
        String str = ""+salt.charAt(0)+salt.charAt(2) + inputPass +salt.charAt(5) + salt.charAt(4);
        //char类型计算会自动转换为int类型
        return md5(str);
    }

    /**
     * Form pass to db pass string.
     * 二次MD5
     * @param formPass the form pass
     * @param salt     the salt
     * @return the string
     */
    public static String formPassToDBPass(String formPass, String salt) {
        //随机的salt
        String str = ""+salt.charAt(0)+salt.charAt(2) + formPass +salt.charAt(5) + salt.charAt(4);
        return md5(str);
    }

    /**
     * Input pass to db pass string.
     * 数据库md5,使用数据库随机salt
     * @param inputPass the input pass
     * @param saltDB    the salt db
     * @return the string
     */
    public static String inputPassToDbPass(String inputPass, String saltDB) {
        String formPass = inputPassToFormPass(inputPass);
        String dbPass = formPassToDBPass(formPass, saltDB);
        return dbPass;
    }

    /**
     * Generate random salt string.
     * 生成随机salt
     * @return the string
     */
    public static String generateRandomSalt() {
        String salt = UUIDUtil.uuid().substring(0,saltLength);
        return salt;
    }

    public static void main(String[] args) {
        System.out.println(generateRandomSalt());
        //d3b1294a61a07da9b49b6e22b2cbd7f9
        System.out.println(inputPassToFormPass("123456"));
        System.out.println(formPassToDBPass(inputPassToFormPass("123456"), salt));
        //b7797cce01b4b131b433b6acf4add449
        System.out.println(inputPassToDbPass("123456", salt));
    }

}
